<template>
  <div>{{ $store.state.counter }}</div>
  <div>{{ counter }}</div>
  <p>counter={{ $store.getters.getCounter }}</p>
  <p>{{ getCounter }}</p>
  <button @click="add">增加</button>
  <button @click="addAsysncClickHandle">异步增加</button>
  <div class="input-container">
    <div class="input-wrapper">
      <input
        type="text"
        v-model="question"
        placeholder="请输入内容"
        @focus="isFocused = true"
        @blur="isFocused = false"
      />
    </div>
    <button class="send-button" @click="chat">
      发送
    </button>
  </div>
  <div>答案：</div>
  <div>{{ answer }}</div>
  <div>历史记录：</div>
  <div>{{history}}</div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapState,mapGetters ,mapMutations,mapActions}=createNamespacedHelpers('global')

import api from "../api/index"

export default {
  data() {
    return {
      inputText: '',
      isFocused: false,
      answer:"",
      question:""
    };
  },
  methods: {
    ...mapMutations(["undateHistory"]),
    ...mapActions(["asyncAddCounter"]),
    sendMessage() {
      // 在这里处理发送逻辑
      console.log('发送消息: ' + this.inputText);
    },
    add() {
      //固定调用方式
    // this.$store.commit("addCounter",10)
    // this.addCounter(20);
    },
    addAsysncClickHandle() {
      // this.$store.dispatch("asyncAddCounter")
        this.asyncAddCounter();
    },
    async chat() {
      try {
        const params = {
          question: this.question,
          history: this.history
        };

        // 调用api中的登录接口
        const response = await api.chat(params);
        
        // 处理登录成功后的逻辑
        console.log("成功",response);
        this.answer=response.response;
        this.undateHistory(response.history);

      } catch (error) {
        // 处理登录失败后的逻辑
        console.error("报错",error);
      }
    }

  },
  //专门来读取vuex的数据
  computed:{
    ...mapState(["counter","history"]),
    ...mapGetters(["getCounter"])
  },
  mounted() {
    // console.log(1);
    // api.chat(
    //   {
    //     "question": "身份证怎么补办",
    //     "history": []
    //   }
    // ).then(res =>{
    //   console.log("拿到数据：")
    //   console.log(res);
    // })
  }
};
</script>

<style scoped>
.input-container {
  border: 1px solid #ccc;
  border-radius: 5px;
  display: flex;
  align-items: center;
  padding: 5px;
}

.input-wrapper {
  flex: 1;
  overflow: hidden;
}

.input-wrapper input {
  border: none;
  outline: none;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 5px;
}

.send-button {
  border: none;
  background-color: transparent;
  outline: none;
  cursor: pointer;
  padding: 5px;
}
</style>